package com.wangtao.firstapp.activity.sife_secondactivity;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.squareup.picasso.Picasso;
import com.wangtao.firstapp.R;
import com.wangtao.firstapp.activity.EditorWishActivity;
import com.wangtao.firstapp.activity.OriginalAuthorActivity;
import com.wangtao.firstapp.activity.ShopDetailsActivity;
import com.wangtao.firstapp.adapters.ACTSifeSecondReviewAdapter;
import com.wangtao.firstapp.adapters.OneSifeSecondLookAdapter;
import com.wangtao.firstapp.custom.FullyLinearLayoutManager;
import com.wangtao.firstapp.modles.CommentsListData;
import com.wangtao.firstapp.modles.OneSifeSecond;
import com.wangtao.firstapp.modles.OneSifeSecondLook;
import com.wangtao.firstapp.utils.DialogUtils;
import com.wangtao.firstapp.utils.HttpUtils;
import com.wangtao.firstapp.utils.ToastUtils;

import org.xutils.common.util.DensityUtil;
import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.util.List;

/**
 * 二级页面-->作者原创页面
 * Created by lanouhn on 16/8/28.
 */
public class OneSifeSecondActivity extends Activity implements View.OnClickListener {


    //用于存作者Id
    private SharedPreferences sp;
    private SharedPreferences.Editor editor;

    private TextView tvcomment, title, author, views, time, collect, authorsife, guanzhu;
    private ImageView pic, logo, logosife;
    private ImageButton back, ivShare;
    private View viewview;

    private LinearLayout lltAuthor;

    //文章，图，卖东西
    private OneSifeSecond oneSifeSecond;
    private LinearLayout ll_wenzhang_one;

    //大家都在看
    private OneSifeSecondLook oneSifeSecondLook;
    private RecyclerView recycierView_look;
    //因“头像”网址所在列表不同，不可复用ACTSifeSecondLookADapter适配器
    private OneSifeSecondLookAdapter oneSifeSecondLookAdapter;

    //评论
    private CommentsListData commentsListData;
    private RecyclerView recycierView_review_content;
    private ACTSifeSecondReviewAdapter actSifeSecondReviewAdapter;

    //标志位
    private int flag = 0;
    //创建自定义Dialog对象，并实例化
    DialogUtils dialogUtils = new DialogUtils(OneSifeSecondActivity.this);

    //创建自定义Toast，并实例化
    ToastUtils toastUtils = new ToastUtils(OneSifeSecondActivity.this);

    private ScrollView mRootScrollView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_sife_second_one);
        initView();
        initData();
        initEvent();
    }

    private void initView() {

        sp = getSharedPreferences("config", Context.MODE_PRIVATE);
        editor = sp.edit();

        viewview = findViewById(R.id.viewview_item_sife_second_essay_one);

        back = (ImageButton) findViewById(R.id.back_act_sife_second_one);
        ivShare = (ImageButton) findViewById(R.id.ivshare_act_sife_second_one);
        tvcomment = (TextView) findViewById(R.id.tvcomment_act_sife_second_one);
        ll_wenzhang_one = (LinearLayout) findViewById(R.id.ll_wenzhang_one);
        title = (TextView) findViewById(R.id.tv_title_one);
        author = (TextView) findViewById(R.id.author_sife_second_essay);
        views = (TextView) findViewById(R.id.views_sife_second_essay);
        pic = (ImageView) findViewById(R.id.pic_sife_second_essay_one);
        logo = (ImageView) findViewById(R.id.logo_sife_second_essay);

        time = (TextView) findViewById(R.id.time_sife_second_essay_one);
        collect = (TextView) findViewById(R.id.collect_sife_second_essay_one);
        authorsife = (TextView) findViewById(R.id.authorsife_second_essay_one);
        guanzhu = (TextView) findViewById(R.id.guanzhu_sife_second_essay_one);
        logosife = (ImageView) findViewById(R.id.logosife_second_essay_one);

        recycierView_look = (RecyclerView) findViewById(R.id.look_sife_second_essay_one);
        recycierView_review_content = (RecyclerView) findViewById(R.id.review_sife_second_essay_one);

        mRootScrollView = (ScrollView) findViewById(R.id.root_item_sife_second_essay_one);
        lltAuthor = (LinearLayout) findViewById(R.id.lltAuthor_second_essay_one);
    }

    private void initData() {

        Intent intent = getIntent();
        //接收当前页面ID,在下边的网址中进行拼接
        String item_ID = intent.getStringExtra("item_ID");

        //文章，图，卖东西
        String urlSecond = "http://open4.bantangapp.com/topic/newInfo";
        String paramsSecond = "app_id=com.jzyd.BanTang&client_id=bt_app_android&client_secret=ffcda7a1c4ff338e05c42e7972ba7b8d&track_user_id=2573914&oauth_token=12977829338e5f953e3d24bcef502b6a&track_deviceid=866479023806507&track_device_info=x600&channel_name=leshi&app_installtime=1471853508&app_versions=5.8.6&os_versions=5.0.2&screensize=1080&v=18&id=" + item_ID + "&trace_id=&relate_pid=&statistics_uv=1&is_night=0";


        try {
            //文章，图，卖东西
            HttpUtils.doPostAsyn(urlSecond, paramsSecond, new HttpUtils.CallBack() {
                @Override
                public void onRequestComplete(String result) {
                    Gson gson_OneSecond = new Gson();
                    oneSifeSecond = gson_OneSecond.fromJson(result, OneSifeSecond.class);
                    if (oneSifeSecond.getData().getContent_list().size() > 0) {
                        handler.sendEmptyMessage(1);
                    } else {
                        handler.sendEmptyMessage(0);
                    }

                }
            });

            //大家都在看
            String urlLook = "http://open4.bantangapp.com/topics/topic/relationRec";
            String paramsLook = "app_id=com.jzyd.BanTang&client_id=bt_app_android&client_secret=ffcda7a1c4ff338e05c42e7972ba7b8d&track_user_id=2573914&oauth_token=12977829338e5f953e3d24bcef502b6a&track_deviceid=866479023806507&track_device_info=x600&channel_name=leshi&app_installtime=1471853508&app_versions=5.8.6&os_versions=5.0.2&screensize=1080&v=18&id=" + item_ID;

            HttpUtils.doPostAsyn(urlLook, paramsLook, new HttpUtils.CallBack() {
                @Override
                public void onRequestComplete(String result) {
                    Gson gson_look = new Gson();
                    oneSifeSecondLook = gson_look.fromJson(result, OneSifeSecondLook.class);
                    if (oneSifeSecondLook.getData().getTopic().size() > 0) {
                        handler.sendEmptyMessage(2);
                    } else {
                        handler.sendEmptyMessage(0);
                    }
                }
            });

            //评论
            String urlReview = "http://open4.bantangapp.com/topics/comment/list";
            String paramsReview = "app_id=com.jzyd.BanTang&client_id=bt_app_android&client_secret=ffcda7a1c4ff338e05c42e7972ba7b8d&track_user_id=2573914&oauth_token=12977829338e5f953e3d24bcef502b6a&track_deviceid=866479023806507&track_device_info=x600&channel_name=leshi&app_installtime=1471853508&app_versions=5.8.6&os_versions=5.0.2&screensize=1080&v=18&page=0&pagesize=20&id=" + item_ID;

            HttpUtils.doPostAsyn(urlReview, paramsReview, new HttpUtils.CallBack() {
                @Override
                public void onRequestComplete(String result) {
                    Gson gson_Review = new Gson();
                    commentsListData = gson_Review.fromJson(result, CommentsListData.class);
                    if (commentsListData.getData().size() > 0) {
                        handler.sendEmptyMessage(3);
                    } else {
                        handler.sendEmptyMessage(0);
                    }

                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:

                    break;
                case 1:

                    time.setText("创建于 " + oneSifeSecond.getData().getDatestr());
                    collect.setText("收藏 " + oneSifeSecond.getData().getLikes());
                    authorsife.setText(oneSifeSecond.getData().getUser().getNickname());
                    Picasso.with(OneSifeSecondActivity.this).load(oneSifeSecond.getData().getUser().getAvatar()).into(logosife);

                    tvcomment.setText(oneSifeSecond.getData().getComments() + "评论");
                    title.setText(oneSifeSecond.getData().getTitle());
                    author.setText(oneSifeSecond.getData().getUser().getNickname());
                    views.setText(oneSifeSecond.getData().getViews());
                    if (!oneSifeSecond.getData().getPic().equals("")) {
                        pic.setVisibility(View.VISIBLE);
                        viewview.setVisibility(View.GONE);
                        Picasso.with(OneSifeSecondActivity.this).load(oneSifeSecond.getData().getPic()).into(pic);
                    }


                    Picasso.with(OneSifeSecondActivity.this).load(oneSifeSecond.getData().getUser().getAvatar()).into(logo);

                    final List<OneSifeSecond.DataBean.ContentListBean> content = oneSifeSecond.getData().getContent_list();
                    for (int i = 0; i < content.size(); i++) {
                        if (content.get(i).getType() == 2) {//文字

                            TextView textView = new TextView(OneSifeSecondActivity.this);
                            textView.setText(content.get(i).getText_content());
                            textView.setTextColor(getResources().getColor(R.color.grayy));
                            textView.setLineSpacing(15, 1.2f);
                            textView.setTextSize(16);
                            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup
                                    .LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                            layoutParams.setMargins(0, 20, 0, 20);
                            textView.setLayoutParams(layoutParams);
                            ll_wenzhang_one.addView(textView);

                        }
                        if (content.get(i).getType() == 1) {//图片

                            ImageView imageView = new ImageView(OneSifeSecondActivity.this);
                            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup
                                    .LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                            layoutParams.setMargins(0, 30, 0, 10);
                            imageView.setLayoutParams(layoutParams);
                            ImageOptions imageOptions = new ImageOptions.Builder()
                                    .setSize(DensityUtil.dip2px(400), DensityUtil.dip2px(400))//图片大小
                                    .setRadius(DensityUtil.dip2px(5))//ImageView圆角半径
                                    .setCrop(true)// 如果ImageView的大小不是定义为wrap_content, 不要crop.
                                    .setImageScaleType(ImageView.ScaleType.CENTER_CROP)
                                    //.setLoadingDrawableId(R.mipmap.ic_launcher)//加载中默认显示图片
                                    // .setFailureDrawableId(R.mipmap.ic_launcher)//加载失败后默认显示图片
                                    .build();
                            x.image().bind(imageView, content.get(i).getImage_url(), imageOptions);

                            // Picasso.with(OneSifeSecondActivity.this).load(content.get(i).getImage_url()).into(imageView);

                            TextView textView = new TextView(OneSifeSecondActivity.this);
                            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup
                                    .LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                            layoutParams.setMargins(0, 30, 0, 10);
                            textView.setLayoutParams(params);
                            textView.setText(content.get(i).getImage_desc());

                            ll_wenzhang_one.addView(imageView);
                            ll_wenzhang_one.addView(textView);
                        }
                        if (content.get(i).getType() == 5) {//卖东西


                            View view = LayoutInflater.from(OneSifeSecondActivity.this).inflate(R.layout.sife_second_view_one, null);

                            RelativeLayout re_sife_second_view_one = (RelativeLayout) view
                                    .findViewById(R.id.re_sife_second_view_one);//
                            RelativeLayout rltLikes_sife_second_view_one= (RelativeLayout) view
                                    .findViewById(R.id.rltLikes_sife_second_view_one);//
                            LinearLayout lltShop_sife_second_view_one= (LinearLayout) view
                                    .findViewById(R.id.lltShop_sife_second_view_one);//

                            //点击后
                            final ImageView ivWish= (ImageView) view.findViewById(R.id.imageview_toast_like);
                            final TextView  tvWish= (TextView) view.findViewById(R.id.textView_sife_second_view_one);

                            //点击前
                            final ImageView ivLikes= (ImageView) view.findViewById(R.id.likes_iv_sife_second_view);
                            final TextView tvLikes= (TextView) view.findViewById(R.id.likes_tv_sife_second_view);

                            ImageView iv_shop = (ImageView) view.findViewById(R.id.iv_shop);
                            TextView tv_title1 = (TextView) view.findViewById(R.id.tv_title1);
                            TextView item_name_sife_second_view_one = (TextView) view
                                    .findViewById(R.id.item_name_sife_second_view_one);
                            TextView price_name_sife_second_view_one = (TextView) view
                                    .findViewById(R.id.price_name_sife_second_view_one);
                            TextView likes_tv_sife_second_view = (TextView) view
                                    .findViewById(R.id.likes_tv_sife_second_view);

                            Picasso.with(OneSifeSecondActivity.this).load(content.get(i).getPic()).into(iv_shop);
                            tv_title1.setText(content.get(i).getItem_subtitle());
                            item_name_sife_second_view_one.setText(content.get(i).getItem_name());
                            price_name_sife_second_view_one.setText(content.get(i).getPrice());
                            likes_tv_sife_second_view.setText(content.get(i).getLikes());
                            ll_wenzhang_one.addView(view);

                            final int j = i;

                            //跳转至，单品详情页面
                            re_sife_second_view_one.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    //获取商品ID
                                    String shop_ID = content.get(j).getProduct_id();
                                    Intent intent1 = new Intent(OneSifeSecondActivity.this, ShopDetailsActivity.class);
                                    intent1.putExtra("shop_iD", shop_ID);
                                    startActivity(intent1);
                                }
                            });

                            // //点击后，切换视图，并Toast，二次点击，弹出Dialog
                            rltLikes_sife_second_view_one.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    if (flag==0){
                                        flag=1;
                                        ivWish.setVisibility(View.VISIBLE);
                                        tvWish.setVisibility(View.VISIBLE);
                                        ivLikes.setVisibility(View.GONE);
                                        tvLikes.setVisibility(View.GONE);
                                        toastUtils.toast(content.get(j).getPic(), 1000);
                                    }else {
                                        AlertDialog.Builder aBuilder= new AlertDialog.Builder(OneSifeSecondActivity.this);
                                        View view = LayoutInflater.from(OneSifeSecondActivity.this)
                                                .inflate(R.layout.likes_wish_dialog, null);
                                        aBuilder.setView(view);
                                        aBuilder.setCancelable(false);
                                        final AlertDialog alertDialog = aBuilder.create();


                                        ImageView bad = (ImageView) view.findViewById(R.id.bad_likes_wish_dialog);//右上角的“X”，点击退出Dialog
                                        //容器，放置“我的喜欢”。点击后退出Dialog,toast
                                        LinearLayout lltLike = (LinearLayout) view.findViewById(R.id.lltLike_likes_wish_dialog);
                                        Button cancel = (Button) view.findViewById(R.id.cancel_likes_wish_dialog);//点击后，取消喜欢，并退出Dialog
                                        TextView found = (TextView) view.findViewById(R.id.found_likes_wish_dialog);//点击后，跳转至 编辑心愿单页面
                                        ImageView shopPhoto = (ImageView) view.findViewById(R.id.shopPhoto_likes_wish_dialog);//商品图片，获取显示
                                        Picasso.with(OneSifeSecondActivity.this).load(content.get(j).getPic()).into(shopPhoto);

                                        //退出Dialog
                                        bad.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                alertDialog.cancel();
                                            }
                                        });

                                        //退出Dialog，在Activity中写取消喜欢
                                        cancel.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                ivWish.setVisibility(View.GONE);
                                                tvWish.setVisibility(View.GONE);
                                                ivLikes.setVisibility(View.VISIBLE);
                                                tvLikes.setVisibility(View.VISIBLE);
                                                flag = 0;
                                                alertDialog.cancel();
                                            }
                                        });

                                        //退出Dialog，并Toast
                                        lltLike.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                toastUtils.toast(content.get(j).getPic(), 1000);
                                                alertDialog.cancel();
                                            }
                                        });

                                        //跳转至，编辑心愿单页面
                                        found.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                Intent intent = new Intent(OneSifeSecondActivity.this, EditorWishActivity.class);
                                                startActivity(intent);
                                            }
                                        });
                                        alertDialog.show();

                                    }
                                }
                            });

                            //购买
                            lltShop_sife_second_view_one.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {

                                    String urlAlter= content.get(j).getUrl();
                                    Uri uriTb = Uri.parse(urlAlter);
                                    Intent intent = new Intent(Intent.ACTION_VIEW, uriTb);
                                    startActivity(intent);

                                }
                            });


                        }
                    }
                    break;
                case 2:
                    //大家都在看
                    oneSifeSecondLookAdapter = new OneSifeSecondLookAdapter(OneSifeSecondActivity.this, oneSifeSecondLook);
                    recycierView_look.setAdapter(oneSifeSecondLookAdapter);
                    recycierView_look.setLayoutManager(new FullyLinearLayoutManager(OneSifeSecondActivity.this));
                    break;

                case 3:
                    //评论
                    actSifeSecondReviewAdapter = new ACTSifeSecondReviewAdapter(OneSifeSecondActivity.this, commentsListData);
                    recycierView_review_content.setAdapter(actSifeSecondReviewAdapter);
                    recycierView_review_content.setLayoutManager(new FullyLinearLayoutManager(OneSifeSecondActivity.this));
                    break;
            }
        }
    };



    private void initEvent() {
        back.setOnClickListener(this);
        tvcomment.setOnClickListener(this);
        ivShare.setOnClickListener(this);
        logo.setOnClickListener(this);
        author.setOnClickListener(this);
        logosife.setOnClickListener(this);
        authorsife.setOnClickListener(this);
        guanzhu.setOnClickListener(this);
    }


    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            //返回上一个页面
            case R.id.back_act_sife_second_one:
                finish();
                break;

            //点击，直达底部评论处
            case R.id.tvcomment_act_sife_second_one:

                mRootScrollView.fullScroll(ScrollView.FOCUS_DOWN);
                break;
            //点击分享
            case R.id.ivshare_act_sife_second_one:
                Toast.makeText(this, "分享", Toast.LENGTH_SHORT).show();
                break;
            //点击作者头像或昵称，进入作者介绍页面

            //跳转至，作者介绍页面
            case R.id.logo_sife_second_essay:
            case R.id.author_sife_second_essay:
            case R.id.logosife_second_essay_one:
            case R.id.authorsife_second_essay_one:

                String author_ID = oneSifeSecond.getData().getUser().getUser_id();
                Intent intent = new Intent(OneSifeSecondActivity.this, OriginalAuthorActivity.class);
                editor.putString("author_iD", author_ID);
                editor.commit();
                startActivity(intent);

                break;

            //关注。一次点击，背景变色。二次点击，，，变回来
            case R.id.guanzhu_sife_second_essay_one:
                if (flag == 0) {
                    guanzhu.setText("已关注");
                    guanzhu.setBackgroundColor(Color.GRAY);
                    flag = 1;
                } else {
                    guanzhu.setText("+ 关注");
                    guanzhu.setBackgroundColor(Color.RED);
                    flag = 0;
                }
                break;


        }
    }
}
